package com.passer.toolbox.common.file.util;

import java.io.File;
import java.util.HashMap;
import java.util.List;

public class MoveFileUtils {

    public static void moveFile(String sourceFilePath, String targetFolderPath) {
        File sourceFile = new File(sourceFilePath);
        if (!sourceFile.exists()) {
            throw new RuntimeException("待移动文件不存在");
        }
        File targetFolder = new File(targetFolderPath);
        if (!targetFolder.exists()) {
            throw new RuntimeException("目标文件夹不存在");
        }
        File targetFile = new File(targetFolder, sourceFile.getName());
        moveFile(sourceFile, targetFile);
    }

    public static void moveFile(String sourceFilePath, String targetFolderPath, String targetFileName) {
        File sourceFile = new File(sourceFilePath);
        if (!sourceFile.exists()) {
            throw new RuntimeException("待移动文件不存在");
        }
        File targetFolder = new File(targetFolderPath);
        if (!targetFolder.exists()) {
            throw new RuntimeException("目标文件夹不存在");
        }
        File targetFile = new File(targetFolder, targetFileName);
        moveFile(sourceFile, targetFile);
    }

    public static void moveFiles(String sourceFolderPath, String sourceFileNameRegex, String targetFolderPath) {
        File sourceFolder = new File(sourceFolderPath);
        if (!sourceFolder.exists()) {
            throw new RuntimeException("待移动文件父目录不存在");
        }
        File targetFolder = new File(targetFolderPath);
        if (!targetFolder.exists()) {
            throw new RuntimeException("目标文件夹不存在");
        }
        System.out.println("匹配待移动文件");
        HashMap<String, List<String>> map = new HashMap<>();
        FileUtils.getFileNames(sourceFolder, map, sourceFileNameRegex);
        System.out.println("待移动文件匹配完成");
        System.out.println("开始移动文件");
        for (List<String> filePathList : map.values()) {
            if (filePathList.size() > 1) {
                StringBuilder stringBuilder = new StringBuilder();
                for (String filePath : filePathList) {
                    stringBuilder.append(filePath).append(",");
                }
                stringBuilder.append("重名文件，无法移动");
                throw new RuntimeException(stringBuilder.toString());
            }
            String filePath = filePathList.get(0);
            File sourceFile = new File(filePath);
            File targetFile = new File(targetFolder, sourceFile.getName());
            moveFile(sourceFile, targetFile);
        }


    }

    public static void moveFile(File sourceFile, File targetFile) {
        System.out.println(sourceFile.getAbsolutePath() + "移动到" + targetFile.getAbsolutePath());
        if (targetFile.exists()) {
            throw new RuntimeException("目标文件夹中已经包含同名文件");
        }
        if (!sourceFile.renameTo(targetFile)) {
            throw new RuntimeException("文件移动失败");
        }
    }
}
